package com.sevenday.mybottomnagivationviewdemo.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.google.android.material.bottomnavigation.BottomNavigationItemView;
import com.google.android.material.bottomnavigation.BottomNavigationMenuView;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.sevenday.mybottomnagivationviewdemo.R;
import com.sevenday.mybottomnagivationviewdemo.adapter.MyPageAdapter;
import com.sevenday.mybottomnagivationviewdemo.fragment.HomeFragment;
import com.sevenday.mybottomnagivationviewdemo.fragment.ImageFragment;
import com.sevenday.mybottomnagivationviewdemo.fragment.MessageFragment;
import com.sevenday.mybottomnagivationviewdemo.fragment.MineFragment;

import java.util.ArrayList;
import java.util.List;

import q.rorbin.badgeview.QBadgeView;

public class BNVVPAddRedIconActivity extends AppCompatActivity {

    private static final String TAG = BNVVPAddRedIconActivity.class.getSimpleName();
    BottomNavigationView navigation;
    ViewPager vp;

    List<Fragment> fragmentList=new ArrayList<>();

    MyPageAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bnvvpadd_red_icon);
        navigation=findViewById(R.id.bnv);
        vp=findViewById(R.id.vp);

        fragmentList.add(HomeFragment.newInstance());
        fragmentList.add(ImageFragment.newInstance());
        fragmentList.add(MessageFragment.newInstance());
        fragmentList.add(MineFragment.newInstance());

        adapter=new MyPageAdapter(getSupportFragmentManager(),fragmentList);

        vp.setAdapter(adapter);


        navigation.setOnNavigationItemSelectedListener(menuItem -> {

            switch (menuItem.getItemId()){
                case R.id.navigation_home:
                    vp.setCurrentItem(0);
                    return true;
                case R.id.navigation_image:
                    vp.setCurrentItem(1);
                    return true;

                case R.id.navigation_msg:
                    vp.setCurrentItem(2);
                    return true;

                case R.id.navigation_mine:
                    vp.setCurrentItem(3);
                    return true;

            }

            return false;
        });



        vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                Log.i(TAG, "onPageScrolled: "+position);
            }

            @Override
            public void onPageSelected(int position) {
                Log.i(TAG, "onPageSelected: "+position);
//                if (prevMenuItem != null) {
//                    prevMenuItem.setChecked(false);
//                } else {
//                    navigation.getMenu().getItem(0).setChecked(false);
//                }
//                navigation.getMenu().getItem(position).setChecked(true);
//                prevMenuItem = navigation.getMenu().getItem(position);

                navigation.setSelectedItemId(navigation.getMenu().getItem(position).getItemId());

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                Log.i(TAG, "onPageScrollStateChanged: "+state);
            }
        });
        //默认选第几个
        navigation.setSelectedItemId(navigation.getMenu().getItem(2).getItemId());


        //获取整个的NavigationView
        BottomNavigationMenuView menuView = (BottomNavigationMenuView) navigation.getChildAt(0);

        //这里就是获取所添加的每一个Tab(或者叫menu)，
        View tab = menuView.getChildAt(3);
        BottomNavigationItemView itemView = (BottomNavigationItemView) tab;

        //加载我们的角标View，新创建的一个布局
        View badge = LayoutInflater.from(this).inflate(R.layout.menu_badge, menuView, false);

        //添加到Tab上
        itemView.addView(badge);


        TextView count = (TextView) badge.findViewById(R.id.tv_msg_count);
        count.setText(String.valueOf(1));
        count.setVisibility(View.VISIBLE);

        //如果没有消息，不需要显示的时候那只需要将它隐藏即可
//        count.setVisibility(View.GONE);

        new Thread(()->{
            try {
                Thread.sleep(2000);
                handler.sendEmptyMessage(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }).start();

    }

    Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //需要在activity创建完成之后才能创建角标
            showBadgeView(navigation,2,2);
        }
    };

    /**
     * BottomNavigationView显示角标
     *
     * @param viewIndex tab索引
     * @param showNumber 显示的数字，小于等于0是将不显示
     */
    private void showBadgeView(BottomNavigationView bottomNavigationView,int viewIndex, int showNumber) {
        // 具体child的查找和view的嵌套结构请在源码中查看
        // 从bottomNavigationView中获得BottomNavigationMenuView
        BottomNavigationMenuView menuView = (BottomNavigationMenuView) bottomNavigationView.getChildAt(0);
        // 从BottomNavigationMenuView中获得childview, BottomNavigationItemView
        if (viewIndex < menuView.getChildCount()) {
            // 获得viewIndex对应子tab
            View view = menuView.getChildAt(viewIndex);
            // 从子tab中获得其中显示图片的ImageView
            View icon = view.findViewById(com.google.android.material.R.id.icon);
            // 获得图标的宽度
            int iconWidth = icon.getWidth();//注意：当直接在oncreate方法中使用值为0，因为整个界面没有创建完成，无法获取这个imageview宽
//            int iconWidth = icon.getLayoutParams().width;
            // 获得tab的宽度/2
            int tabWidth = view.getWidth() / 2;//注意：当直接在oncreate方法中使用值为0，因为整个界面没有创建完成，无法获取这个BottomNavigationItemView宽
            // 计算badge要距离右边的距离
            int spaceWidth = tabWidth - iconWidth;



            // 显示badegeview
            new QBadgeView(this).bindTarget(view).setGravityOffset(spaceWidth, 3, false).setBadgeNumber(showNumber);
        }
    }


}
